package com.common.core.logs.appender;


import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggerContextVO;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import com.common.core.logs.marker.MarkerHandle;
import org.slf4j.Marker;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * @auther zhangwj
 * @date 2021/11/27 下午9:53
 * @desc 异步记录标记日志
 */
public class SyncMarkerAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {

    private final static String OPEN_MARKER = "OPEN_MARKER";
    private final static String OPEN_MARKER_VALUE = "false";

    @Override
    protected void append(ILoggingEvent loggingEvent) {
        LoggerContextVO loggerContext = loggingEvent.getLoggerContextVO();
        if (null == loggerContext) {
            return;
        }
        Map<String, String> map = loggerContext.getPropertyMap();
        if (CollectionUtils.isEmpty(map)) {
            return;
        }
        String openMarker = map.get(OPEN_MARKER);
        if (OPEN_MARKER_VALUE.equals(openMarker)) {
            return;
        }
        Marker marker = loggingEvent.getMarker();
        if (null == marker) {
            return;
        }
        MarkerHandle.Handle handle = MarkerHandle.MAP.get(marker.getName());
        if (null == handle) {
            return;
        }
        handle.doHandle(loggingEvent, marker.getName());
    }
}
